package com.ulinkle.ulinkle_muhf.presenter;

import android.content.Context;
import android.content.DialogInterface;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

import com.speedata.libuhf.IUHFService;
import com.ulinkle.ulinkle_muhf.uhf.UHFUtil;
import com.ulinkle.ulinkle_muhf.view.IMain;

/**
 * @Description: java类作用描述
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class MainPresenter {
    private IUHFService iuhfService;
    private IMain mIMain;

    private boolean buzzerIsCheck = false;

    public MainPresenter(IMain iMain) {
        mIMain = iMain;
    }

    /**
     * 初始化UHF
     * @param applicationContext
     */
    public  void initUhf(Context applicationContext){
         iuhfService = UHFUtil.getInstance().getIuhfService();
        if (iuhfService != null) {
            SystemClock.sleep(1000);
        } else {
            UHFUtil.getInstance().setIuhfService(applicationContext);
            buzzerIsCheck = true;
             new CheckIsNullThread().start();
             iuhfService = UHFUtil.getInstance().getIuhfService();
            if (iuhfService == null) {
                return;
            }
             try {
                UHFUtil.isOpenDev = openDev();
                if (UHFUtil.isOpenDev) {
                    UHFUtil.getInstance().initParam(applicationContext);
                } else {
                    return;
                }
                  Log.d("UHFService", "startService==main==");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 上电开串口
     * Power on and open serial port
     */
    private boolean openDev() {
        if (!UHFUtil.isOpenDev) {
            if (iuhfService.openDev() != 0) {
                mIMain.openFail();
                UHFUtil.isOpenDev = false;
                return false;
            } else {
                Log.d("UHFService", "上电成功");
            }
        }
        UHFUtil.isOpenDev = true;
        return true;
    }


 private class CheckIsNullThread extends Thread {
        @Override
        public void run() {
            while (buzzerIsCheck) {
                if (UHFUtil.getInstance().getIuhfService() == null) {
                   mIMain.floatWarn();
                }
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
